package com.jyxd.web.controller.ZZhongZheng;

import com.alibaba.fastjson.JSON;
import com.jyxd.web.data.ZSqlSettings.form.ZZhongZhengSearchForm;
import com.jyxd.web.service.ZSqlSettings.ZSqlSettingsService;
import com.jyxd.web.util.HttpCode;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/zzhongzheng")
public class ZZhongZhengController {

    @Resource
    private ZSqlSettingsService zsqlSettingsService;

    @PostMapping("/list/")
    public String test(@RequestBody ZZhongZhengSearchForm zZhongZhengSearchForm) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        List<Map<String, Object>> list = zsqlSettingsService.getList(zZhongZhengSearchForm);

        if (list != null && !list.isEmpty()) {
            json.put("msg", "查询成功");
            if (zZhongZhengSearchForm.getSqlType() != 2) {
                // 提取所有键为 '项目名' 的值
                List<String> projectNames = list.stream()
                        .map(map -> {
                            Object projectNameObj = map.get("项目名");
                            if (projectNameObj instanceof Date) {
                                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                return dateFormat.format((Date) projectNameObj);
                            }
                            return projectNameObj != null ? projectNameObj.toString() : null;
                        })
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                // 提取所有键为 '项目值' 的值
                List<Object> projectValues = list.stream()
                        .map(map -> map.get("项目值"))
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                // 创建一个 Map 来存储两个 List
                Map<String, Object> result = new HashMap<>();
                result.put("projectNames", projectNames);
                result.put("projectValues", projectValues);
                json.put("data", result);
            } else {
                // 使用 Stream API 获取所有键名
                // 将 Set 转换为 List
                List<String> allKeys = list.stream()
                        .flatMap(map -> map.keySet().stream()).distinct().collect(Collectors.toList());
                // 创建一个 Map 来存储
                Map<String, Object> result = new HashMap<>();
                result.put("allKeys", allKeys);
                result.put("list", list);
                json.put("data", result);
            }

        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }
}
